package com.miracle.java2110.exception;

import com.miracle.java2110.common.R;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@Component
@ControllerAdvice
@ResponseBody
public class CustomExceptionResolver {

    /**
     * 自定义异常
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomerException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public R handleHttpMessageNotReadableException(CustomerException ex) {
        return new R(444, ex.getMessage());
    }

    /**
     * 缺少请求参数异常
     * @param ex
     * @return
     */
    @ExceptionHandler(ArithmeticException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public R handleHttpMessageNotReadableException(ArithmeticException ex) {
        return new R(444, ex.getMessage());
    }

    /**
     * 缺少请求参数异常
     * @param ex
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleHttpMessageNotReadableException(MissingServletRequestParameterException ex) {
        return new R(400, "缺少必要请求参数");
    }

    /**
     * 系统异常 预期以外异常
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleUnexpectedServer(Exception ex) {
        return new R(500, "系统发生异常，请联系管理员");
    }

}
